<template>
  <el-form :inline="true" :model="searchParam" @submit.native.prevent>
    <!-- 循环生成表单填写项 -->
    <template v-for="(item, index) in fields" :key="index">
      <el-form-item :label="item.label">
        <!-- 下拉类型 -->
        <el-select
          clearable
          @clear="searchList"
          v-if="item.type === 'select'"
          v-model="searchParam[item.key]"
        >
          <el-option
            v-for="(subItem, sonIndex) in item.options.list"
            :key="sonIndex"
            :label="subItem.label"
            :value="subItem.value"
            @change="
              (value) => {
                searchChange(value, item.key)
              }
            "
          />
        </el-select>
        <!-- 下拉树形数据 -->

        <el-select
          clearable
          @clear="searchList"
          v-if="item.type === 'selectTree'"
          v-model="searchParam[item.key]"
        >
          <el-option hidden key="id" :value="value" :label="label"></el-option>
          <el-tree
            node-key="id"
            class="elTree"
            :data="item.options.list"
            :props="{ children: 'children', label: 'name' }"
            :expand-on-click-node="false"
            default-expand-all
            @node-click="
              (e) => {
                clicktree(e, item.key)
              }
            "
          ></el-tree>
        </el-select>
        <!-- 单选 -->
        <template v-else-if="item.type === 'radio'">
          <el-radio-group v-model="searchParam[item.key]">
            <el-radio
              v-for="(subItem, index) in item.options.list"
              :key="index"
              :label="subItem.value"
              >{{ subItem.label }}</el-radio
            >
          </el-radio-group>
        </template>
        <!-- 多选 -->
        <template v-else-if="item.type === 'checkbox'">
          <el-checkbox-group v-model="searchParam[item.key]">
            <el-checkbox
              v-for="(subItem, index) in item.options.list"
              :key="index"
              :label="subItem.value"
              >{{ subItem.label }}</el-checkbox
            >
          </el-checkbox-group>
        </template>
        <!-- 时间选择 -->
        <template v-else-if="/^date-/.test(item.type)">
          <el-date-picker
            v-model="searchParam[item.key]"
            type="date"
            :placeholder="item.placeholder || '请选择'"
            :editable="false"
            value-format="YYYY-MM-DD"
            size="large"
          >
          </el-date-picker>
        </template>
        <!-- 时间选择年 -->
        <template v-else-if="item.type === 'year'">
          <el-date-picker
            v-model="searchParam[item.key]"
            type="year"
            :placeholder="item.placeholder || '请选择'"
            :editable="false"
            value-format="YYYY"
            size="large"
          >
          </el-date-picker>
        </template>
        <!-- 时间范围选择 -->
        <template v-else-if="item.type === 'datetimerange'">
          <el-date-picker
            v-model="searchParam[item.key]"
            type="datetimerange"
            class="search_time"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            size="large"
          >
          </el-date-picker>
        </template>
        <!-- 输入框范围选择 -->
        <template v-else-if="item.type === 'scopeInput'">
          <div class="scopeInput">
            <el-input
              clearable
              :type="item.type"
              v-model="searchParam[item.key.split('-')[0]]"
              @input="changeInput(item.key)"
            ></el-input>
            <span style="color: #ccc">～</span>
            <el-input
              clearable
              :type="item.type"
              v-model="searchParam[item.key.split('-')[1]]"
              @input="changeInput(item.key)"
            ></el-input>
          </div>
        </template>
        <!-- 数字输入框 -->
        <template v-else-if="item.type === 'number'">
          <el-input
            clearable
            type="text"
            onkeyup="value=value.replace(/[^\d]/g,'')"
            :class="item.isTitle ? 'form_title' : ''"
            v-model="searchParam[item.key]"
          ></el-input>
        </template>
        <!-- 输入框 -->
        <template v-else-if="item.type === 'input' || item.type === 'textarea'">
          <el-input
            :type="item.type"
            :class="item.isTitle ? 'form_title' : ''"
            :style="{width:item.width===undefined?'100%':item.width+'px'}"
            v-model="searchParam[item.key]"
            @clear="searchList"
            :placeholder="item.placeholder"
            clearable
          ></el-input>
        </template>
        <!-- 级联选择 -->
        <template v-else-if="item.type === 'cascader'">
          <el-cascader
            :options="item.options.list"
            v-model="searchParam[item.key]"
            @clear="searchList"
            :props="item.checkStrictly"
            clearable
          ></el-cascader>
        </template>
      </el-form-item>
    </template>
    <!-- 特殊搜索组件插槽 -->
    <slot name="individuation"></slot>
    <el-form-item>
      <el-button
        type="primary"
        color="#fc702b"
        style="color: #fff"
        @click="searchList"
        >查询</el-button
      >
      <el-button color="#f0f0f0" style="color: #000000" @click="resetHandle"
        >重置</el-button
      >
      <slot name="btn-add"></slot>
    </el-form-item>
    <slot name="right-btn"></slot>
  </el-form>
</template>

<script setup>
import { reactive, ref, onBeforeMount } from 'vue'
import {
  ElSelect,
  ElMessage,
  ElInput,
  ElTree,
  ElCascader,
  ElDatePicker,
  ElButton,
  ElRadio,
  ElCheckbox,
  ElForm,
  ElFormItem
} from 'element-plus'
let value = ref('')
let label = ref('')
const props = defineProps({
  fields: {
    type: Array,
    default: () => []
  }
})
const searchParam = ref({})
//输入框范围校验
const inputKey = ref(null)
//范围校验
const changeInput = (key) => {
  console.log(key)

  inputKey.value = key
}

const searchChange = (value, key) => {}
const emits = defineEmits(['searchList','resetList'])
// 搜索列表
const searchList = () => {
  // 单个时间选择验证
  let isItemDate = props.fields.find((item) => /^date-/.test(item.type))
  if (isItemDate && !redioDateVali()) {
    return
  }
  let str = null
  let rule = []
  if (inputKey.value) {
    //输入框范围校验
    str = props.fields.filter((item) => item['key'] == inputKey.value)
    rule = inputKey.value.split('-')
  }

  if (searchParam.value[rule[0]] && searchParam.value[rule[1]]) {
    if (searchParam.value[rule[0]] > searchParam.value[rule[1]]) {
      return $message.error(`开始${str[0].label}不能大于结束${str[0].label}`)
    } else {
      emits('searchList', getSearchParams())
    }
  } else {
    emits('searchList', getSearchParams())
  }
}
// 初始化搜索表单
const initForm = () => {
  for (let item of props.fields) {
    if (item.type == 'datetimerange') {
      searchParam.value[item.key] = item.defaultValue || []
    } else {
      searchParam.value[item.key] = item.defaultValue || ''
    }
    if (item.type == 'scopeInput') {
      searchParam.value[item.key.split('-')[0]] = item.defaultValue || ''
      searchParam.value[item.key.split('-')[1]] = item.defaultValue || ''
    }
  }
}
// 两侧时间选择验证
const redioDateVali = () => {
  let sKey = props.fields.find((e) => e.type == 'date-s')
  let eKey = props.fields.find((e) => e.type == 'date-e')
  let startDate = sKey ? searchParam.value[sKey.key] : ''
  let endDate = eKey ? searchParam.value[eKey.key] : ''
  if (startDate && !endDate) {
    ElMessage({
      message: '请选择结束时间',
      type: 'warning'
    })
    return false
  }
  if (!startDate && endDate) {
    ElMessage({
      message: '请选择开始时间',
      type: 'warning'
    })

    return false
  }
  if (startDate > endDate) {
    ElMessage({
      message: '开始时间不得大于结束时间',
      type: 'warning'
    })

    return false
  }
  return true
}

// 重置搜索参数
const resetHandle = () => {

  initForm()
  searchList()
  emits('resetList')
}
// 获取查询参数
const getSearchParams = () => {
  let s = searchParam.value
  let params = {}
  for (let key in s) {
    if (!s[key] && s[key]!==0) continue
    let item = props.fields.find((e) => {
      if (e.key == key || e.key == inputKey.value) {
        return true
      }
    })
    if (!item) continue
    // 时间范围选择单独处理
    if (item.type == 'datetimerange') {
      if (s[key].length) {
        params[key.split('-')[0]] = s[key][0]
        params[key.split('-')[1]] = s[key][1]
      }
    } else {
      params[key] = s[key]
    }
  }
  return params
}
const clicktree = (event, key) => {
  searchParam[key] = event.id
  value = event.id
  label = event.name
}
onBeforeMount(() => {
  initForm()
})
defineExpose({
  searchList,
  resetHandle,
  getSearchParams
})
</script>
<style lang="scss" scoped>
.el-form-item{
  width: auto !important;
}
:deep(.el-date-editor) {
  width: 100%;
  height: 100%;

  .el-input__wrapper {
    width: 100%;
    height: 100%;
  }
}
</style>
